package pers.qianyu.module.image.schedule;

import cn.hutool.core.util.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.data.redis.core.*;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.module.core.constants.*;
import pers.qianyu.module.image.service.*;

import java.util.*;

/**
 * @author mizzle rain
 * @date 2021-03-01 17:57
 */
@Component
public class DailyRankScheduleTask {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ImageService imageService;

    /**
     * 每天凌晨零点钟，将排行榜数据刷到数据库，并清空排行榜
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void backup() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .rangeWithScores(CacheConstants.DAILY_RANK, 0, -1);
        if (Objects.isNull(typedTuples)) {
            return;
        }
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String idStr = typedTuple.getValue();
            idStr = StrUtil.subAfter(idStr, CacheConstants.IMAGE_ID, false);
            long id = Long.parseLong(idStr);
            long views = typedTuple.getScore().longValue();
            imageService.addViews(id, views);
        }
        redisTemplate.delete(CacheConstants.DAILY_RANK);
    }
}
